package tree;

import java.util.Currency;

/**
 * 二叉树
 *
 * @author TANGYE
 * @2021/1/12 9:49
 */
public class BinaryTree<T> {

    public static final String DLR = "DLR";

    private Node<T> root;
    private Node<T> insertNode;

    public BinaryTree() {
        root = new Node<>();
        insertNode = root;
    }

    public BinaryTree(T t) {
        root = new Node<>(t);
        insertNode = root;
    }

    private class Node<T> {
        Node<T> lChild;
        Node<T> rChild;
        T date;

        public Node() {
            date = null;
            lChild = null;
            rChild = null;
        }

        public Node(T date) {
            this.date = date;
            lChild = null;
            rChild = null;
        }
    }

    /**
     * 遍历二叉树
     *
     * @param tMode 遍历方式
     * @return void
     * @author TANGYE
     * @date 2021/1/12 10:51
     */
    public void traversal(String tMode) {
        switch (tMode) {
            case DLR:
                traversalDLR(root);
            default:
                traversalDLR(root);
        }
    }

    public Node addLChild(T t, Node<T> parentNode) {
        Node lChildNode = new Node(t);
        if (null == parentNode) {
            return null;
        }
        if (parentNode.lChild == null) {
            parentNode.lChild = lChildNode;
            return lChildNode;
        }
        lChildNode.lChild = parentNode.lChild;
        parentNode.lChild = lChildNode;
        return lChildNode;
    }

    public Node addRChild(T t, Node<T> parentNode) {
        Node rChildNode = new Node(t);
        if (null == parentNode) {
            return null;
        }
        if (parentNode.rChild == null) {
            parentNode.rChild = rChildNode;
            return rChildNode;
        }
        rChildNode.rChild = parentNode.rChild;
        parentNode.rChild = rChildNode;
        return rChildNode;
    }

    /**
     * 前序遍历
     *
     * @param node 开始遍历节点
     * @return void
     * @author TANGYE
     * @date 2021/1/12 10:51
     */
    private void traversalDLR(Node<T> node) {
        if (node == null) {
            return;
        }
        System.out.println(node.date);
        traversalDLR(node.lChild);
        traversalDLR(node.rChild);
    }

    public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree();
        BinaryTree.Node nodeA = binaryTree.addLChild("A", binaryTree.root);
        BinaryTree.Node nodeB = binaryTree.addRChild("B", binaryTree.root);
        BinaryTree.Node nodeC = binaryTree.addLChild("C", nodeA);
        BinaryTree.Node nodeD = binaryTree.addRChild("D", nodeA);
        binaryTree.traversal(BinaryTree.DLR);
    }
}
